package com.ego.item.controller;

import com.ego.common.PageResult;
import com.ego.item.pojo.Brand;
import com.ego.item.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/brand")
@CrossOrigin
public class BrandController {
    @Autowired
    private BrandService brandService;
    @GetMapping("/page")
    public ResponseEntity<PageResult<Brand>> page(@RequestParam("pageNo") Integer pageNo,
                                                  @RequestParam("pageSize") Integer pageSize,
                                                  @RequestParam("sortBy") String sortBy,
                                                  @RequestParam("descending") Boolean descending,
                                                  @RequestParam("key") String key){
        PageResult<Brand> result=brandService.page(pageNo,pageSize,sortBy,descending,key);
        if (result==null || result.getItems().size()==0){
            ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(result);
    }

    @PostMapping
    public ResponseEntity<Void> save(Brand brand,@RequestParam("cids") List<Integer> cids){
        brandService.save(brand,cids);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @PutMapping
    public ResponseEntity<Void> update(Brand brand,@RequestParam("cids") List<Integer> cids){
        brandService.update(brand, cids);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable("id") Long id){
        brandService.deleteById(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/cid/{cid}")
    public ResponseEntity<List<Brand>> seleteBrand(@PathVariable("cid") Long cid){
        List<Brand> result = brandService.findByCid(cid);
        if (result==null){
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(result);
    }
}
